package com.ly.mpayment.rest.up.sanchongmao;

import com.alibaba.fastjson.JSONObject;
import com.ly.mpayment.core.secuity.MD5;
import com.ly.mpayment.core.util.*;
import com.ly.mpayment.persist.entity.UpOrder;
import com.ly.mpayment.persist.entity.UpShopInfo;
import com.ly.mpayment.persist.service.downrechargeflow.IDownRechargeFlowService;
import com.ly.mpayment.persist.service.downshopinfo.IDownShopInfoService;
import com.ly.mpayment.persist.service.uporder.IUporderService;
import com.ly.mpayment.persist.service.upshopinfo.IUpShopInfoService;
import com.ly.mpayment.rest.recharge.RechargeRest;
import org.apache.log4j.Logger;
import org.mortbay.util.MultiMap;
import org.mortbay.util.UrlEncoded;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.QueryParam;

@Component
@Path("sanchongmao")
public class SanChongMaoRest {

    Logger logger = Logger.getLogger(SanChongMaoRest.class);

    @Autowired
    IUporderService upOrderService;

    @Autowired
    private ThreadPoolTaskExecutor taskExecutor;

    @Autowired
    IDownRechargeFlowService flowService;

    @Autowired
    IDownShopInfoService shopService;

    @Autowired
    IUpShopInfoService upShopInfoService;

    public void queryOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("proxyUserId",shop.getAppId());
        data.put("proxyOrderId",order.getUporderuuid());
        data.put("proxyReqTime", new DateUtils().toTimeStamp());
        data.put("orderRechargeTime",  new DateUtils(order.getCreatetime()).toTimeStamp());
        final String sign = StringSort.doSign(data);
        data.put("sign", MD5.md5(sign + shop.getUpkey()));
        logger.info("queryOrder_sanchongmao:"+shop.getOrderStatusAddress().concat("?").concat(sign).concat("&sign=")+data.getString("sign"));
        String result = HttpClient.httpGetUrl(shop.getOrderStatusAddress().concat("?").concat(sign).concat("&sign=")+data.getString("sign"));
        logger.info("resultsanchongmao:"+result);
        if(result != null){
            //code=200&desc=success&proxyOrderId=805ded9d2806459aacc1e37c351da15a&phoneNumber=15972752266&rechargeAmount=100&
            // orderStatus=0&voucher=100101101001812170957183012345
            MultiMap map = parceString(result);
            if(map != null){
                //订单状态 // 0失败1成功 2处理中
                if(map.getString("code").equals("200") && map.getString("orderStatus").equals("1")){
                    order.setRemark( map.containsKey("voucher") ? map.getString("voucher") : map.getString("desc"));
                    RechargeRest.successUpOrder.add(order);
                } else if(map.getString("code").equals("200") && map.getString("orderStatus").equals("0")){
                    order.setRemark(map.getString("desc"));
                    RechargeRest.failtUpOrder.add(order);
                }else {
                    upOrderService.updateUpOrderMsg(order, "",map.getString("desc"));
                }
            }else{
                upOrderService.updateUpOrderMsg(order, "","转换失败:"+result);
            }
        }else{
            //不处理 走查询 确认
            upOrderService.updateUpOrderMsg(order, "","提单失败:"+result);
            logger.info("提单失败"+order.getUpphonenum());
        }
    }
    public void commitOrder(UpOrder order, UpShopInfo shop) {
        JSONObject data = new JSONObject();
        data.put("proxyUserId",shop.getAppId());
        data.put("phoneNumber",order.getUpphonenum());
        data.put("rechargeAmount",order.getUpShopPro().getUpfacevalue());
        data.put("rechargeType","1");
        data.put("proxyOrderId",order.getUporderuuid());
        data.put("proxyReqTime", new DateUtils().toTimeStamp());
        data.put("callbackURL",shop.getOrderCallAddress());
        final String sign = StringSort.doSign(data);
        //运营商(cmcc:话费移动,cucc:话费联通,ctcc:话费电信,lmcc:流量移动,lucc:流量联通,ltcc:流量电信,gmcc:固话移动,gucc:固话联通,gtcc:固话电信,cnpc:中石油,snpc:中石化,otit:其他权益类),该字段不参与签名
        //运营商类型，联通-lt 移动-yd 电信-dx,不参与验证，必填
        //2edb5b9c-9f99-11e7-9dc0-fcaa1456507e 中国移动
        //2ee16927-9f99-11e7-9dc0-fcaa1456507e 中国联通
        //2ee70961-9f99-11e7-9dc0-fcaa1456507e 中国电信
        data.put("isp",order.getOperators().equals("2edb5b9c-9f99-11e7-9dc0-fcaa1456507e") ? "cmcc" :
                order.getOperators().equals("2ee16927-9f99-11e7-9dc0-fcaa1456507e") ? "cucc" :
                        order.getOperators().equals("2ee70961-9f99-11e7-9dc0-fcaa1456507e") ? "ctcc" : "xx");
        data.put("proxyAmount",order.getRechargeamount());
        data.put("sign", MD5.md5( sign + shop.getUpkey()));
        logger.info("commitOrder_sanchongmao:"+shop.getOrderCommitAddress().concat("?").concat(sign).concat("&sign=")+data.getString("sign"));
        String result = HttpClient.httpGetUrl(shop.getOrderCommitAddress().concat("?").concat(sign).concat("&sign=")+data.getString("sign"));
        logger.info("commitOrder_result:"+result);
        if(result != null){
            //code=200&desc=success&proxyOrderId=5036d02b65544c7c9abb3937106383c8&myOrderId=9357afe5203b4880a9daa3cd9a967487&myOrderTime=20170101121240&proxyAmount=9.945
            MultiMap map = parceString(result);
            if(map != null){
                if(map.getString("code").equals("200")){
                    upOrderService.updateUpOrderMsg(order, map.getString("myOrderId"), map.getString("desc"));
                }else if(
                        map.getString("code").equals("301") ||
                                map.getString("code").equals("302") ||
                                map.getString("code").equals("303") ||
                                map.getString("code").equals("304") ||
                                map.getString("code").equals("305") ||
                                map.getString("code").equals("306") ||
                                map.getString("code").equals("307") ||
                                map.getString("code").equals("308") ||
                                map.getString("code").equals("309") ||
                                map.getString("code").equals("310") ||
                                map.getString("code").equals("311") ||
                                map.getString("code").equals("312") ||
                                map.getString("code").equals("313") ||
                                map.getString("code").equals("314")){
                    order.setRemark(map.getString("desc"));
                    RechargeRest.failtUpOrder.add(order);
                }else{
                    upOrderService.updateUpOrderArtificial(order, "",map.getString("desc"));
                }
            }else{
                upOrderService.updateUpOrderArtificial(order, "","转换失败:"+result);
            }
        }else{
            //不处理 走查询 确认
            upOrderService.updateUpOrderArtificial(order, "","提单失败:"+result);
            logger.info("提单失败"+order.getUpphonenum());
        }
    }

    private MultiMap parceString(String str){
        MultiMap map = new MultiMap();
        UrlEncoded.decodeTo(str, map, "utf-8");
        return map;
    }


    @Path("callBack")
    @GET
    //myOrderId=9357afe5203b4880a9daa3cd9a967487&
    // myReqTime=20170101121212&orderStatus=1&
    // proxyOrderId=955258258&
    // proxyUserId=test&voucher=100101101001812170957183012345&sign=aaad865954c572473b402614f3cfee28
    public String callBack(@QueryParam("myOrderId") String myOrderId, @QueryParam("orderStatus") String orderStatus, @QueryParam("proxyOrderId") String proxyOrderId,
                           @QueryParam("myReqTime") String myReqTime, @QueryParam("sign") String sign, @QueryParam("voucher") String voucher, @QueryParam("proxyUserId") String proxyUserId){

        logger.info("sanchongmaocallBack:"+myOrderId+","+sign+","+orderStatus+","+proxyOrderId+","+voucher+","+proxyUserId +","+myReqTime);
        if(!StringUtils.isBlank(proxyOrderId)){
            UpOrder order = upOrderService.findById(proxyOrderId);
            if(order != null ){
                //订单状态 // 0失败1成功 2处理中
                if (order != null && orderStatus.equals("1") && order.getStatus() == Config.status[0]) {
                    order.setRemark(voucher == null ? orderStatus : voucher);
                    RechargeRest.successUpOrder.add(order);
                    return "success";
                }else if(order != null && order.getStatus() == Config.status[0] && orderStatus.equals("0") ){
                    order.setRemark(orderStatus);
                    RechargeRest.failtUpOrder.add(order);
                    return "success";
                }else{
                    logger.info("sanchongmaocallBack_not_found_order:" + proxyOrderId );
                }
            }else {
                logger.info("未找到订单:"+proxyOrderId);
            }
        }
        return "failt";
    }
}
